import { useState, useEffect } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import axios from 'axios'
import './index.css'

// 支付状态接口
interface PaymentStatus {
  code: string
  msg: string
  buyerLogonId: string
  buyerPayAmount: string
  buyerUserId: string
  buyerUserType: string
  invoiceAmount: string
  outTradeNo: string
  pointAmount: string
  receiptAmount: string
  sendPayDate: string
  totalAmount: string
  tradeNo: string
  tradeStatus: string
  traceId: string
}

function PaymentSuccess() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const [paymentStatus, setPaymentStatus] = useState<PaymentStatus | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // 从URL参数获取订单号
  const orderNo = searchParams.get('orderNo')

  // 获取支付状态
  const getPaymentStatus = async () => {
    if (!orderNo) {
      setError('订单号不存在')
      setLoading(false)
      return
    }

    try {
      const endpoints = [
        'http://blogapi.shbwyz.com/order/getPayStatus',
        'http://172.27.2.110/order/getPayStatus'
      ]

      let handled = false
      for (const url of endpoints) {
        try {
          const response = await axios.post(url, { out_trade_no: orderNo }, {
            timeout: 10000,
            headers: { 'Content-Type': 'application/json' }
          })
          const payload: any = response.data
          console.log('支付状态响应:', payload)

          const code = typeof payload?.code === 'number' ? String(payload.code) : payload?.code
          const data = payload?.data || payload
          const innerCode = typeof data?.code === 'number' ? String(data.code) : data?.code
          const tradeStatus = (data?.tradeStatus || data?.trade_status || '').toString()

          if ((code === '10000' && data) || (code === '200' && innerCode === '10000')) {
            if (tradeStatus === 'TRADE_SUCCESS') {
              const mapped: PaymentStatus = {
                code: innerCode || code || '10000',
                msg: data?.msg || payload?.msg || 'Success',
                buyerLogonId: data?.buyerLogonId || '',
                buyerPayAmount: data?.buyerPayAmount || '',
                buyerUserId: data?.buyerUserId || '',
                buyerUserType: data?.buyerUserType || '',
                invoiceAmount: data?.invoiceAmount || '',
                outTradeNo: data?.outTradeNo || orderNo,
                pointAmount: data?.pointAmount || '',
                receiptAmount: data?.receiptAmount || '',
                sendPayDate: data?.sendPayDate || '',
                totalAmount: data?.totalAmount || '',
                tradeNo: data?.tradeNo || '',
                tradeStatus: tradeStatus || 'TRADE_SUCCESS',
                traceId: data?.traceId || ''
              }
              setPaymentStatus(mapped)
              // 写入本地“已缴费记录”
              try {
                const key = 'paidRecords'
                const prev = JSON.parse(localStorage.getItem(key) || '[]') as any[]
                const record = {
                  outTradeNo: mapped.outTradeNo,
                  totalAmount: mapped.totalAmount,
                  tradeNo: mapped.tradeNo,
                  sendPayDate: mapped.sendPayDate,
                  department: '门诊外一科',
                  doctor: '刘医师'
                }
                const exists = prev.some((r) => r.outTradeNo === record.outTradeNo)
                const next = exists ? prev : [record, ...prev].slice(0, 50)
                localStorage.setItem(key, JSON.stringify(next))
              } catch {}
              setError(null)
              handled = true
              break
            } else {
              setError(`当前交易状态：${tradeStatus || '未知'}`)
              handled = true
              break
            }
          }
        } catch (e) {
          continue
        }
      }
      if (!handled) {
        setError('获取支付状态失败: 接口无有效数据')
      }
    } catch (error: unknown) {
      console.error('获取支付状态失败:', error)
      setError('获取支付状态失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    getPaymentStatus()
  }, [orderNo])

  // 复制订单号
  const copyOrderNo = () => {
    if (paymentStatus?.outTradeNo) {
      navigator.clipboard.writeText(paymentStatus.outTradeNo)
      alert('订单号已复制到剪贴板')
    }
  }

  // 获取交易状态文本
  const getTradeStatusText = (status: string) => {
    switch (status) {
      case 'WAIT_BUYER_PAY':
        return '等待买家付款'
      case 'TRADE_CLOSED':
        return '交易关闭'
      case 'TRADE_SUCCESS':
        return '交易支付成功'
      case 'TRADE_FINISHED':
        return '交易结束'
      default:
        return status
    }
  }

  if (loading) {
    return (
      <div className="payment-success">
        <div className="loading">
          <div className="loading-spinner"></div>
          <div className="loading-text">正在获取支付状态...</div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="payment-success">
        <div className="error-state">
          <div className="error-icon">❌</div>
          <div className="error-text">{error}</div>
          <button className="retry-button" onClick={getPaymentStatus}>
            重试
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="payment-success">
      {/* 顶部导航 */}
      <div className="header">
        <div className="header-content">
          <button className="back-button" onClick={() => navigate(-1)}>
            ‹
          </button>
          <div className="title">缴费订单详情</div>
          <div className="header-actions">
            <span className="action-icon">⋯</span>
            <span className="action-icon">◎</span>
          </div>
        </div>
      </div>

      {/* 支付状态 */}
      <div className="payment-status">
        <div className="status-icon">✓</div>
        <div className="status-text">已缴费</div>
      </div>

      {/* 条形码 */}
      <div className="barcode-section">
        <div className="barcode">📊</div>
        <div className="barcode-number">{paymentStatus?.outTradeNo || '20200101001598Z'}</div>
        <div className="barcode-tip">取药或检查时请出示此码</div>
      </div>

      {/* 缴费信息 */}
      <div className="payment-info">
        <div className="section-title">缴费信息</div>
        <div className="info-item">
          <span className="label">登记号:</span>
          <span className="value">20200101001598Z</span>
        </div>
        <div className="info-item">
          <span className="label">就诊人:</span>
          <span className="value">王小柯</span>
        </div>
        <div className="info-item">
          <span className="label">就诊科室:</span>
          <span className="value">门诊外一科</span>
        </div>
        <div className="info-item">
          <span className="label">开单医生:</span>
          <span className="value">刘医师</span>
        </div>
        <div className="info-item">
          <span className="label">开单时间:</span>
          <span className="value">2020-01-01 10:20:36</span>
        </div>
      </div>

      {/* 费用明细 */}
      <div className="cost-details">
        <div className="section-title">费用明细</div>
        
        {/* 药品费用 */}
        <div className="cost-category">
          <div className="category-header medicine">
            <span>请前往一楼门诊药房2号窗口取药</span>
          </div>
          <div className="prescription-info">
            <span>处方号(20200101032)</span>
          </div>
          <div className="cost-items">
            <div className="cost-item">1、葆宫止血颗粒*3盒 ¥50.13</div>
            <div className="cost-item">2、维生素B1*2瓶 ¥20.00</div>
            <div className="cost-item">3、维生素B2*2瓶 ¥10.00</div>
            <div className="cost-item">4、维生素E*2瓶 ¥10.00</div>
            <div className="cost-item">5、维生素C*2瓶 ¥10.00</div>
          </div>
        </div>

        {/* 检查费用 */}
        <div className="cost-category">
          <div className="category-header examination">
            <span>请前往门诊三楼放射科进行检查</span>
          </div>
          <div className="prescription-info">
            <span>检查单号(20200101133)</span>
          </div>
          <div className="cost-items">
            <div className="cost-item">1、CT ¥200.00</div>
            <div className="cost-item">2、上腹部CT平扫 ¥220.00</div>
          </div>
        </div>

        <div className="total-amount">合计: ¥520.13</div>
      </div>

      {/* 订单信息 */}
      <div className="order-info">
        <div className="section-title">订单信息</div>
        <div className="info-item">
          <span className="label">订单号:</span>
          <span className="value">{paymentStatus?.outTradeNo || '2021010156256894'}</span>
          <button className="copy-button" onClick={copyOrderNo}>复制</button>
        </div>
        <div className="info-item">
          <span className="label">订单流水号:</span>
          <span className="value">{paymentStatus?.tradeNo || '400012021010156256894'}</span>
        </div>
        <div className="info-item">
          <span className="label">订单金额:</span>
          <span className="value">¥{paymentStatus?.totalAmount || '520.13'}</span>
        </div>
        <div className="info-item">
          <span className="label">订单状态:</span>
          <span className="value">{getTradeStatusText(paymentStatus?.tradeStatus || 'TRADE_SUCCESS')}</span>
        </div>
        <div className="info-item">
          <span className="label">支付方式:</span>
          <span className="value">支付宝支付</span>
        </div>
        <div className="info-item">
          <span className="label">下单时间:</span>
          <span className="value">2020-01-01 10:23:36</span>
        </div>
        <div className="info-item">
          <span className="label">支付时间:</span>
          <span className="value">{paymentStatus?.sendPayDate || '2020-01-01 10:25:10'}</span>
        </div>
      </div>
    </div>
  )
}

export default PaymentSuccess
